package com.SoilMM.controller;


import com.SoilMM.entity.UserEntity;
import com.SoilMM.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("doLogin")
    public Map<String,Object> doLogin(@RequestBody UserEntity userEntity, HttpSession session){
        Map<String,Object> map=new HashMap<>();

        if (userService.doLogin(userEntity))
        {
            session.setAttribute("loginUser",userEntity);
            map.put("message","登录成功");
        }
        else {
            map.put("message","登录失败");
        }

        return map;
    }


    @RequestMapping("selectAllUser")
    public Map<String,Object> selectAllUser(){
        Map<String,Object> map=new HashMap<>();
        List<UserEntity> list=new ArrayList<>();

        list=userService.list();
        map.put("data",list);

        return map;
    }

    @RequestMapping("saveUser")
    public Map<String,Object> saveUser(@RequestBody UserEntity user){
        Map<String,Object> map=new HashMap<>();

        System.out.println(user.toString());
        if(userService.saveOrUpdate(user))
        {
            map.put("message","保存成功");
        }
        else {
            map.put("message","保存失败");
        }

        return map;
    }

    @RequestMapping("deleteUser")
    public Map<String,Object> deleteUser(int id)
    {
        Map<String,Object> map=new HashMap<>();
        if (userService.removeById(id))
        {
            map.put("message","删除成功");
        }
        else {
            map.put("message","删除失败");
        }
        return map;
    }

    @RequestMapping("/search")
    public Map<String,Object> search(String userName){
        Map<String,Object> map=new HashMap<>();
        List<UserEntity> list=userService.search(userName);

        if (list.size()>0)
        {
            map.put("list",list);
            map.put("message","查询成功");
        }
        else {
            map.put("message","查询失败");
        }

        return map;
    }

}

